package com.jf3q.common.utils;

import com.jf3q.common.constant.SysConstant;
import com.jf3q.common.exception.JfException;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author:xiaojie
 * @create: 2023-05-07 22:54
 * @Description:jwt工具类
 */
@Component
public class JwtTokenUtil {
    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.expiration}")
    private Long expiration;

    public String getToken(String username){
        Map<String,Object> map = new HashMap<>();
        map.put("typ","JWT");
        return Jwts.builder().setHeaderParams(map)
                .setSubject(username)
                .setExpiration(new Date(System.currentTimeMillis()+expiration*1000))
                .signWith(SignatureAlgorithm.HS256,secret).compact();
    }

    /**
     * 校验token的合法性
     * @return
     */
    public Boolean validateToken(String token ){
        try {
            Claims body = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
            return true;
        } catch (ExpiredJwtException e) {
            e.printStackTrace();
            throw new JfException(SysConstant.CANCEL_TOKEN,"token过期");
        } catch (UnsupportedJwtException e) {
            e.printStackTrace();
            return false;
        } catch (MalformedJwtException e) {
            e.printStackTrace();
            return false;
        } catch (SignatureException e) {
            e.printStackTrace();
            throw new JfException(SysConstant.ILLEGAL_TOKEN,"验签失败");

        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            return false;
        }


    }


    /**
     * 根据token拿到用户名
     * @param token
     * @return
     */
    public String getUserNameFromToken(String token) {
        Claims body = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        return  body.getSubject();
    }
}
